// File: jmcomic-core/src/main/java/dev/jukomu/common/base/mapper/MapperFactory.java
package dev.jukomu.common.base.mapper;

import dev.jukomu.common.base.registry.ShutdownHookManager;

import java.io.IOException;

/**
 * 对应Python的MapperFactory，用于创建Mapper实例。
 */
public class MapperFactory {

    /**
     * 获取一个Mapper实例。
     *
     * @param filepath         Mapper管理的文件路径
     * @param separator        键值对分隔符
     * @param loadAfterCreated 是否在创建后立即加载数据
     * @param saveAtExit       是否在JVM退出时自动保存数据
     * @return Mapper实例
     * @throws IOException 如果加载失败
     */
    public static Mapper<String, String> getMapper(String filepath, String separator, boolean loadAfterCreated, boolean saveAtExit) throws IOException {
        FileMapper mapper = new FileMapper(filepath, separator);

        if (loadAfterCreated) {
            mapper.load();
        }

        if (saveAtExit) {
            // 注册JVM Shutdown Hook，在程序退出时调用mapper.save()
            ShutdownHookManager.register(() -> {
                try {
                    mapper.save();
                } catch (IOException e) {
                    System.err.println("Failed to save mapper data on exit: " + e.getMessage());
                    e.printStackTrace();
                }
            }, "MapperSaveHook-" + filepath.hashCode()); // 使用文件路径的哈希作为Hook名称
        }

        return mapper;
    }

    /**
     * 获取一个Mapper实例，使用默认分隔符','。
     *
     * @param filepath         Mapper管理的文件路径
     * @param loadAfterCreated 是否在创建后立即加载数据
     * @param saveAtExit       是否在JVM退出时自动保存数据
     * @return Mapper实例
     * @throws IOException 如果加载失败
     */
    public static Mapper<String, String> getMapper(String filepath, boolean loadAfterCreated, boolean saveAtExit) throws IOException {
        return getMapper(filepath, ",", loadAfterCreated, saveAtExit);
    }
}